import { open, Database } from 'sqlite';
import ResultDTO from "../../../../src/model/ResultDTO";
const sqlite3 = require('sqlite3').verbose();

//创建信息表：
const sqlCreate = `CREATE TABLE IF NOT EXISTS connect_info (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    connectName VARCHAR(400) NOT NULL,
    host VARCHAR(40) NOT NULL,
    port INTEGER NOT NULL,
    user VARCHAR(100) NOT NULL,
    password VARCHAR(100) NOT NULL,
    type VARCHAR(100) NOT NULL
    );


`;

// 导入sqlite3库和类型定义

// 定义接口，以便可以在其他代码中引用以获得类型检查
export interface IDatabase {
    open(): Promise<Database>;
    close(): Promise<void>;
    run(query: string, params?: any[]): Promise<void>;
    get<T>(query: string, params?: any[]): Promise<T | undefined>;
    all<T>(query: string, params?: any[]): Promise<T | undefined>;
}
class SQLiteDB implements IDatabase {
    private db: Database | null = null;
    private readonly filename: string;

    constructor(filename: string) {
        this.filename = filename;
    }

    async open(): Promise<Database> {
        if (this.db) {
            return this.db;
        }
        this.db = await open({
            filename: this.filename,
            driver: sqlite3.Database,
        });
        return this.db;
    }

    async close(): Promise<void> {
        if (this.db) {
            await this.db.close();
            this.db = null;
        }
    }

    async run(query: string, params?: any[]): Promise<any> {
        if (!this.db) {
            await this.open();
        }
        let result = this.db?.run(query, params);

        console.log("query:", query, " result", result)
        return result;
    }


    async get<T>(query: string, params?: any[]): Promise<T | undefined> {
        if (!this.db) {
            await this.open();
        }
        let result = await this.db?.get<T>(query, params);
        console.log("query:", query, " result", result)
        return result;
    }

    async all<T>(query: string, params?: any[]): Promise<T | undefined> {
        if (!this.db) {
            await this.open();
        }
        return this.db?.all<T>(query, params);
    }
}
const sqliteDB = new SQLiteDB("./data/data.sqlite")
// 定义一个Database类，实现IDatabase接口
sqliteDB.run(sqlCreate).then(res=>{

}).catch(res=>{
    console.log("创建表失败", res)
})
// sqliteDB.all("select * from connect_info order by id asc").then(res => {
//     console.log("sqlite-get-connect-info-list", res);
// }).catch(err => {
// })
export default sqliteDB;
